class Simulator::SimulationsController < ApplicationController
	layout 'simulator/simulator'
	def new
		@system = System.find_by_id(params[:system_id])
		if @system.nil?
			flash[:notice] = "You must use a valid system"
			redirect_to :controller => 'systems', :action => 'index'
		end
	end
	
	def view
 		@graph = open_flash_chart_object(500,250, "/simulator/simulations/scatter/#{params[:id]}")     
	end
		
	def scatter
		simulation = Simulation.find(params[:id])
		planets= []
		planet_type_id = BodyType.find(:first, :conditions => { :name => 'planet' }).id
		test_particles = []
		test_particle_type_id = BodyType.find(:first, :conditions => { :name => 'test_particle' }).id
		
		simulation.simulation_bodies.each do |body|
			body.simulation_data.each do |data|
				if body.body_type.id == planet_type_id
					planets << { data[0].to_sym => [data[1], data[2]] }
				elsif body.body_type.id == test_particle_type_id
					test_particles << { data[0].to_sym => [data[1], data[2]] }
				end
			end
		end

		g = Graph.new
		g.title("Simulation #{simulation.name}", '{font-size: 26px;}')

		g.scatter(planets, 3, '#736aff', 'planets', 12)
		g.set_tool_tip("Semi-major-axis:#x_label#<br>Eccentricity:#val#")
		g.set_x_offset(false)
		g.set_y_label_style(10, '#9933cc')
		g.set_y_label_steps(10)
		g.set_x_label_style(10, '#9933cc')
		g.set_x_legend('Semi-major-axis')
		g.set_y_min(0)
		g.set_y_max(0.5)
		g.set_x_min(0)
		g.set_x_max(5)
		render :text => g.render
	end

	def create
		simulation = Simulation.create(params[:simulation])
		integration_parameter = IntegrationParameter.create_integration_parameter(simulation.id)
		small_body_parameter = SmallBodyParameter.create_small_body_parameter(simulation.id)
		SimulationBody.add_planets(simulation)
				
		if simulation and integration_parameter and small_body_parameter
			flash[:notice] = "Simulation created"
			redirect_to_system(simulation.system_id)
		else
			flash[:notice] = "An error ocurred while creating this simulation"
		end
	end
	
	def destroy
		@simulation = Simulation.find(params[:simulation_id])
		@simulation.integration_parameter.destroy
		@simulation.small_body_parameter.destroy
		@simulation.destroy
		flash[:notice] = "simulation deleted"
		redirect_to_system(params[:system_id])
	end
	
	def redirect_to_system(system_id)
		redirect_to :controller => 'systems', :action => :show, :id => system_id
	end

	def add_planets_to_simulation_bodies
	end
end
